﻿using Adnc.Application.Shared.Dtos;
using Adnc.Application.Shared.Services;
using Adnc.Application.Shared.WeChat;
using Adnc.Infra.Caching;
using Adnc.Infra.Helper;
using Adnc.Infra.IRepositories;
using Adnc.Shared.Consts;
using Adnc.Shared.RpcServices.Rtos.Sys;
using Adnc.Shared.RpcServices.Services;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using WYT.Usr.Application.Contracts.Dtos;
using WYT.Usr.Application.Contracts.Dtos.User;
using WYT.Usr.Application.Contracts.Services;
using WYT.Usr.Repository.Entities;

namespace WYT.Usr.Application.Services
{
    /// <summary>
    /// 用户服务
    /// </summary>
    public class UserAppService : AbstractAppService, IUserAppService
    {
        private readonly IConfiguration _config;

        private readonly IEfRepository<User> _userRepository;

        private readonly IEfRepository<Wallet> _walletRepository;

        private readonly IEfRepository<WithdrawalsRecord> _withdrawalsRecordRepository;

        private readonly IEfRepository<UserRelation> _userRelationRepository;

        private readonly IEfRepository<UserGradeLog> _userGradeLogRepository;

        private readonly IEfRepository<UserCommission> _userCommissionRepository;

        private readonly IEfRepository<UserUpgradeApply> _userUpgradeApplyRepository;

        private readonly IEfRepository<UserPerformance> _userPerformanceRepository;

        private readonly ISysRpcService _sysRpcService;

        private readonly IRedisProvider _redisProvider;

        private readonly WeChatService _weChatService;

        /// <summary>
        /// 用户服务
        /// </summary>
        /// <param name="userRepository"></param>
        /// <param name="walletRepository"></param>
        /// <param name="withdrawalsRecordRepository"></param>
        /// <param name="userRelationRepository"></param>
        /// <param name="userGradeLogRepository"></param>
        /// <param name="userUpgradeApplyRepository"></param>
        /// <param name="userPerformanceRepository"></param>
        /// <param name="userCommissionRepository"></param>
        /// <param name="sysRpcService"></param>
        /// <param name="redisProvider"></param>
        /// <param name="config"></param>
        /// <param name="weChatService"></param>
        public UserAppService(IEfRepository<User> userRepository,
            IEfRepository<Wallet> walletRepository
            , IEfRepository<WithdrawalsRecord> withdrawalsRecordRepository
            , IEfRepository<UserRelation> userRelationRepository
            , IEfRepository<UserGradeLog> userGradeLogRepository
            , IEfRepository<UserUpgradeApply> userUpgradeApplyRepository
            , IEfRepository<UserPerformance> userPerformanceRepository
            , IEfRepository<UserCommission> userCommissionRepository
            , ISysRpcService sysRpcService
            , IRedisProvider redisProvider
            , IConfiguration config
            , WeChatService weChatService)
        {
            _userRepository = userRepository;
            _walletRepository = walletRepository;
            _withdrawalsRecordRepository = withdrawalsRecordRepository;
            _userRelationRepository = userRelationRepository;
            _userGradeLogRepository = userGradeLogRepository;
            _userUpgradeApplyRepository = userUpgradeApplyRepository;
            _userPerformanceRepository = userPerformanceRepository;
            _userCommissionRepository = userCommissionRepository;
            _sysRpcService = sysRpcService;
            _redisProvider = redisProvider;
            _config = config;
            _weChatService = weChatService;
    }

        /// <summary>
        /// 用户单量检查并升级
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<bool>> UserUpgradeCheck(UserUpgradeCheckDto dto)
        {
            var extends = await _userRepository.Where(c => dto.UserIds.Contains(c.Id)).ToListAsync();
            List<UserGradeLog> logs = new List<UserGradeLog>();
            foreach (var item in extends)
            {
                int newGrade = item.Grade;

                if (item.ProxyIntegral >= 1000)
                {
                    if (item.Grade < 5 && item.IsUpgrade)
                    {
                        var user = _userRelationRepository.Where(c => c.Ancestor == item.Id && c.Level == 1).Select(c => c.Descendant).ToList();
                        if (!user.Any())
                            break;
                        var ux = _userRepository.Where(c => user.Contains(c.Id)).OrderByDescending(c => c.ProxyIntegral).ToList();
                        ux.RemoveAt(0);
                        var count = ux.Sum(c => c.ProxyIntegral);
                        if (count >= 200)
                        {
                            newGrade = 5;
                        }
                        else if (item.Grade < 4)
                        {
                            newGrade = 4;
                        }
                    }
                }
                else if (item.ProxyIntegral >= 500)
                {
                    if (item.Grade < 4 && item.IsUpgrade)
                    {
                        newGrade = 4;
                    }
                }
                else if (item.ProxyIntegral >= 50)
                {
                    if (item.Grade < 3 && item.IsUpgrade)
                    {
                        newGrade = 3;
                    }
                }
                else if (item.ProxyIntegral > 0 && item.IsUpgrade)
                {
                    newGrade = 2;
                }

                if (item.Grade < newGrade)
                {
                    logs.Add(new UserGradeLog
                    {
                        Id = IdGenerater.GetNextId(),
                        UserId = item.Id,
                        Mode = 1,
                        Describe = "单量升级",
                        ChangeFrontGrade = item.Grade,
                        ChangeLaterGrade = newGrade,
                        ChangeTime = DateTime.Now,
                        OrderSource = dto.OrderId,
                    });
                    item.Grade = newGrade;
                    await _userRepository.UpdateAsync(item, UpdatingProps<User>(x => x.Grade));

                }
            }
            if (logs.Count > 0)
                await _userGradeLogRepository.InsertRangeAsync(logs);
            return true;
        }

        /// <summary>
        /// 获取用户的基本信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<UserBaseInfoDto>> GetUserBaseInfo(long userId)
        {
            var userinfo = await _userRepository.FindAsync(c => c.Id == userId);
            var wallet = await _walletRepository.FindAsync(c => c.UserId == userId);
            var wa =  _withdrawalsRecordRepository.Where(c => c.UserId == userId && c.State == 0).Sum(c =>c.Amount);
            
            var communityIntegral = 0;
            var user = _userRelationRepository.Where(c => c.Ancestor == userId && c.Level == 1).Select(c => c.Descendant).ToList();            
            if (user.Any())
            {
                var ux = _userRepository.Where(c => user.Contains(c.Id)).OrderByDescending(c => c.ProxyIntegral).ToList();
                ux.RemoveAt(0);
                communityIntegral = ux.Sum(c => c.ProxyIntegral);
            }

           bool.TryParse(_config["WYT:CheckSuperior"],out bool check);

            var result = new UserBaseInfoDto
            {
                Id = userinfo.Id,
                Nickname = userinfo.Nickname,
                Head = userinfo.Head,
                Account = userinfo.Account,
                Gender = userinfo.Gender,
                Tel = userinfo.Tel,
                Grade = userinfo.Grade,
                ProxyIntegral = userinfo.ProxyIntegral,
                ConsumptionPoints = userinfo.ConsumptionPoints,
                Balance = (wallet?.Balance) ?? 0,
                ShoppingMoney = (wallet?.ShoppingMoney) ?? 0,
                WithdrawalAmount = wa,
                CommunityIntegral = communityIntegral,
                UnionID = userinfo.UnionID,
            };
            if (check)
                result.Superior = !(userinfo.SuperiorUser == 0 || userinfo.SuperiorUser == WYTConst.defaultSuperior);
            result.HasUpgradeApplication = await _userUpgradeApplyRepository.AnyAsync(x => x.UserId == userId && x.State == 0);
            return result;
        }

        /// <summary>
        /// 获取用户授权信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<UserAuthorizeCodeDto>> GetUserAuthorizeCode(long userId)
        {
            var usr = await _userRepository.FindAsync(userId);
            if (usr.AuthorizationCode.IsNull())
            {
                Random random = new Random();
                string strRandom = random.Next(10000, 99999).ToString(); //生成编号 
                usr.AuthorizationCode = $"SQ{DateTime.Now.ToString("yyyyMMddHHmmssffff")}{strRandom}";
                usr.AuthorizationDate = DateTime.Now;
                await _userRepository.UpdateAsync(usr, UpdatingProps<User>(x => x.AuthorizationCode, x => x.AuthorizationDate));
            }
            return new UserAuthorizeCodeDto()
            {
                Name = usr.Nickname,
                Code = usr.AuthorizationCode,
                Date = usr.AuthorizationDate.Value,
                Grade = usr.Grade,
            };
        }

        /// <summary>
        /// 跟新用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> UpdateUserInfor(long userId, UserEncryptedInfoDto input)
        {
            try
            {
                var response = await _weChatService.GetJsCode2Session(input.Code);
                if (!response.IsSuccessful())
                    return Problem(null, response.ErrorMessage);
                else
                {
                    var userinfo =  EncryptHelper.DecodeEncryptedDataToEntityEasy<DecodedUserInfo>(response.SessionKey, input.EncryptedData, input.Iv);
                    var user = await _userRepository.FindAsync(userId);
                    user.Nickname = userinfo.nickName;
                    user.Gender = userinfo.gender;
                    user.Country = userinfo.country;
                    user.Province = userinfo.province;
                    user.City = userinfo.city;
                    user.Head = userinfo.avatarUrl;
                    user.UnionID = response.UnionId;
                    await _userRepository.UpdateAsync(user, UpdatingProps<User>(x => x.Nickname, x => x.Gender, x => x.Country, x => x.Province,
                        x => x.City, x => x.Head, x => x.AppletOpenID, x => x.UnionID));
                }
                return AppSrvResult();
            }
            catch (Exception ex)
            {
                return Problem(HttpStatusCode.BadRequest, ex.Message);
            }
        }

        /// <summary>
        /// 跟新用户电话号码
        /// </summary>
        /// <param name="input"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> UpdateUserPhoneNumber(UserEncryptedInfoDto input, long userId)
        {
            var response = await _weChatService.GetJsCode2Session(input.Code);
            if (!response.IsSuccessful())
                return Problem(null, response.ErrorMessage);
            else
            {
                var phoneNumber = EncryptHelper.DecodeEncryptedDataToEntityEasy<DecodedPhoneNumber>(response.SessionKey, input.EncryptedData, input.Iv);
                var user = await _userRepository.FindAsync(userId);
                if (!string.IsNullOrEmpty(phoneNumber.phoneNumber))
                {
                    await _userRepository.UpdateAsync(new User { Id = user.Id, Tel = phoneNumber.phoneNumber }, UpdatingProps<User>(x => x.Tel));
                }
                else
                    return Problem(HttpStatusCode.BadRequest, "更新电话号码失败");
            }
            return AppSrvResult();
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<bool>> SendUserCode(long userId)
        {
            var data = await _redisProvider.StringGetAsync("pwr" + userId);
            if (data.IsNull())
            {
                var user = await _userRepository.FindAsync(userId);
                if (string.IsNullOrEmpty(user.Tel))
                    return Problem(HttpStatusCode.BadRequest, "请先绑定电话号码");

                Random rad = new Random();
                int code = rad.Next(1000, 10000);
                string smsCodeTemp = "{\"code\":\"" + code + "\"}";
                var smsResponse = await _sysRpcService.SendSms(new SendSmsRto { Tel = user.Tel, Temp = "SMS_175536463", TempParam = smsCodeTemp });
                if (!smsResponse.IsSuccessStatusCode)
                    return Problem(HttpStatusCode.BadRequest, "服务异常");
                if (!smsResponse.Content)
                    return false;

                await _redisProvider.StringSetAsync("pwc" + user.Id, code.ToString(), new TimeSpan(0, 5, 0));
                await _redisProvider.StringSetAsync("pwr" + user.Id, "1", new TimeSpan(0, 1, 0));
                return true;
            }
            else
                return Problem(null, "一分钟只能发送一次短信");
        }

        /// <summary>
        /// 验证码验证
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<bool>> CodeVerify(long userId,string input)
        {
            var code = await _redisProvider.StringGetAsync("pwc" + userId);
            if (code.IsNull() || code != input)
                return Problem(null, "验证码不正确");
            await _redisProvider.KeyDelAsync("pwc" + userId);
            return true;
        }

        /// <summary>
        /// 发送修改电话号码的验证码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="phone">电话号码</param>
        /// <returns></returns>
        public async Task<AppSrvResult> SendChangePhoneCode(long userId,string phone)
        {
            var data = await _redisProvider.StringGetAsync("pr" + userId);
            if (data.IsNull())
            {
                Random rad = new Random();
                int code = rad.Next(1000, 10000);
                string smsCodeTemp = "{\"code\":\"" + code + "\"}";
                var smsResponse = await _sysRpcService.SendSms(new SendSmsRto { Tel = phone, Temp = "SMS_175536463", TempParam = smsCodeTemp });
                if (!smsResponse.IsSuccessStatusCode)
                    return Problem(HttpStatusCode.BadRequest, "服务异常");
                if (!smsResponse.Content)
                    return Problem(HttpStatusCode.BadRequest, "发送失败");

                await _redisProvider.StringSetAsync("pc" + userId, code.ToString(), new TimeSpan(0, 5, 0));
                await _redisProvider.StringSetAsync("pr" + userId, "1", new TimeSpan(0, 1, 0));
                return AppSrvResult();
            }
            else
                return Problem(null, "一分钟只能发送一次短信");
        }

        /// <summary>
        /// 修改电话号码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> ChangePhone(long userId, TelChangeDto input)
        {
            var user = await _userRepository.FindAsync(userId);
            var code = await _redisProvider.StringGetAsync("pc" + userId);
            if (code.IsNull() || code != input.Code)
                return Problem(null, "验证码不正确");
            await _redisProvider.KeyDelAsync("pc" + userId);

            if (user.Tel.Equals(input.Tel))
                return new AppSrvResult();
            var exists = await  _userRepository.AnyAsync(x => x.Tel == input.Tel);
            if(exists)
                return Problem(null, "电话号码已存在，不能重复绑定");
            await _userRepository.UpdateAsync(new User() { Id = userId, Tel = input.Tel }, UpdatingProps<User>(x => x.Tel));
            return new AppSrvResult();
        }

        /// <summary>
        /// 添加上级
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="Superior"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> AddSuperior(long userId, long Superior)
        {
            var user = await _userRepository.FindAsync(userId);
            if (user.SuperiorUser != WYTConst.defaultSuperior)
                return AppSrvResult();
            //上级
            var super = await _userRepository.FindAsync(x => x.Account == Superior);
            if (super == null)
                return Problem(null, "上级不存在");
            user.SuperiorUser = super.Id;        

            //用户所有下级
            var ancestor = await _userRelationRepository.Where(x => x.Ancestor == user.Id).ToListAsync();
            //上级的所有上级
            var subRelation = await _userRelationRepository.Where(c => c.Descendant == super.Id).ToListAsync();
            subRelation.Add(new UserRelation { Ancestor = super.Id,Level = 0});

            List<UserRelation> userRelations = new List<UserRelation>();
            foreach (var relation in subRelation)
            {
                userRelations.Add(new UserRelation
                {
                    Id = IdGenerater.GetNextId(),
                    Ancestor = relation.Ancestor,
                    Descendant = user.Id,
                    Level = relation.Level + 1,
                    CreateTime = DateTime.Now
                });
                foreach (var item in ancestor)
                {
                    userRelations.Add(new UserRelation
                    {
                        Id = IdGenerater.GetNextId(),
                        Ancestor = relation.Ancestor,
                        Descendant = item.Descendant,
                        Level = relation.Level +  item.Level + 1,
                        CreateTime = DateTime.Now
                    });
                }
            }

            var ids = ancestor.Select(x => x.Descendant).ToList();
            ids.Add(userId);
            await _userRelationRepository.DeleteRangeAsync(x => ids.Contains(x.Descendant) && x.Ancestor == WYTConst.defaultSuperior);
            await _userRepository.UpdateAsync(user, UpdatingProps<User>(x => x.SuperiorUser));
            await _userRelationRepository.InsertRangeAsync(userRelations);

            return AppSrvResult();
        }

        /// <summary>
        /// 获取用户的交易密码
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<string>> GetWithdrawalPassword(long userId)
        {
            var user = await _userRepository.FindAsync(c => c.Id == userId);
            if (user == null)
                Problem(HttpStatusCode.NotFound);

            return user.WithdrawalPassword ?? string.Empty;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<UserInforDto>> GetUserInfor(long userId)
        {
            var user = await _userRepository.FindAsync(userId);
            return Mapper.Map<UserInforDto>(user);
        }

        /// <summary>
        /// 修改用户交易密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="newWord"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> ChangeWithdrawalPassword(long userId, string newWord)
        {
            var user = await _userRepository.FindAsync(userId);
            user.WithdrawalPassword = HashHelper.GetHashedString(HashType.MD5,newWord,false);
            await _userRepository.UpdateAsync(user, UpdatingProps<User>(c => c.WithdrawalPassword));
            return AppSrvResult();
        }

        /// <summary>
        /// 获取用户等级
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<int>> GetUserGrade(long userId)
        {
            var user = await _userRepository.FindAsync(userId);
            if (user == null)
                return Problem(HttpStatusCode.NotFound);
            return user.Grade;
        }

        /// <summary>
        /// 获取用户OpenId
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<string>> GetUserOpenId(long userId)
        {
            var user = await _userRepository.FindAsync(c => c.Id == userId);
            return user?.AppletOpenID;
        }

        /// <summary>
        /// 获取用户名称和头像
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<List<UserNameAndHeadDto>>> GetUserNameAndHead(long[] userIds)
        {
            return await _userRepository.Where(c => userIds.Contains(c.Id))
                .Select(c => new UserNameAndHeadDto
                {
                    Id = c.Id,
                    Name = c.Nickname,
                    Head = c.Head,
                }).ToListAsync();
        }

        /// <summary>
        /// 用户升级申请
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<bool>> UserUpgradeApply(long userId, UserUpgradeApplyDto input)
        {
            if (!input.PaymentUrl.Any())
                return Problem(null, "请上传保证金截图");

            var usr = await _userRepository.FindAsync(x =>x.Id == userId);

            var user = _userRelationRepository.Where(c => c.Ancestor == userId && c.Level == 1).Select(c => c.Descendant).ToList();
            if (!user.Any())
                return Problem(null, "还未满足条件，不能升级");
            var ux = _userRepository.Where(c => user.Contains(c.Id)).OrderByDescending(c => c.ProxyIntegral).ToList();
            ux.RemoveAt(0);
            var count = ux.Sum(c => c.ProxyIntegral);

            int newgrade = 0;
            if (usr.ProxyIntegral >= 24000 && count >= 6000 && usr.IsUpgrade)
                newgrade = 7;
            else if (usr.ProxyIntegral >= 6000 && count >= 1000 && usr.IsUpgrade)
                newgrade = 6;
            if (newgrade < 6 || newgrade <= usr.Grade)
                return Problem(null, "还未满足条件，不能升级");
            var exit = await _userUpgradeApplyRepository.AnyAsync(x => x.UserId == userId && x.State == 0);
            if (exit)
                return Problem(null, "您还有未处理的升级申请，请勿重复提交");

            await _userUpgradeApplyRepository.InsertAsync(new UserUpgradeApply
            {
                Id = IdGenerater.GetNextId(),
                UserId = userId,
                Phone = input.Phone,
                UserName = input.UserName,
                BeforeGrade = usr.Grade,
                TargetGrade = newgrade,
                ApplyTime = DateTime.Now,
                PaymentVoucher = JsonSerializer.Serialize(input.PaymentUrl),
                State = 0,
                ReceivableAmount = newgrade == 6 ? 3000m: 10000m
            });

            //发送短信
            if (!string.IsNullOrEmpty(usr.Tel))
            {
                var grade = newgrade switch
                {
                    2 => "V0创客",
                    3 => "V1区代",
                    4 => "V2县代",
                    5 => "V3市代",
                    6 => "V4省代",
                    7 => "V5董事",
                    _ => ""
                };

                string smsCodeTemp = "{\"code\":\"" + $"{usr.Account}" + "\",\"grade\":\"" + $"{grade}" + "\"}";
                await _sysRpcService.SendSms(new SendSmsRto()
                {
                    Tel = usr.Tel,
                    Temp = "SMS_219395588",
                    TempParam = smsCodeTemp
                });
            }

            return true;
        }

        /// <summary>
        /// 获取用户团队信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<TeamInfoDto>> GetUserTeamInfor(long userId)
        {
            var date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            TeamInfoDto result = new TeamInfoDto();

            var user = await _userRepository.FindAsync(userId);
            result.TotalPerformance = user.ProxyIntegral;

            //用户推荐人
            var Sup = await _userRepository.FindAsync(x => x.Id == user.SuperiorUser);
            result.Superior = new TeamMemberInfoDto
            {
                Id = Sup.Id,
                Account = Sup.Account,
                NickName = Sup.Nickname,
                Head = Sup.Head,
                Grade = Sup.Grade,
                JoinTime = Sup.CreatTime,
                Tel = Sup.Tel
            };

            //团队人数
            result.AllTeamCount = await  _userRelationRepository.Where(x => x.Ancestor == userId).CountAsync();
            var subIds = await _userRelationRepository.Where(x => x.Ancestor == userId && x.Level == 1).Select(x => x.Descendant).ToListAsync();
            result.DirectCount = subIds.Count;
            if(subIds.Count > 1)
                result.SmallAreaPerformance = _userRepository.Where(x => subIds.Contains(x.Id)).OrderByDescending(x => x.ProxyIntegral).Skip(1).Sum(x => x.ProxyIntegral);

            //单量转盒数
            result.TotalPerformance /=  5;
            result.SmallAreaPerformance /= 5;
            result.Brokerage = _userCommissionRepository.Where(x => x.UserId == userId  && x.State == 1 && x.ArrivalTime >= DateTime.Now.Date && x.ArrivalTime < DateTime.Now.Date.AddDays(1).Date).Sum(x => x.Amount);

            return result;

        }

        /// <summary>
        /// 分页查询用户团队成员
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<PageModelDto<TeamMemberInfoDto>>> TeamMemberSearch(long userId, TeamMemberSearchPagedDto input)
        {
            var count = 0;
            var data = new List<TeamMemberInfoDto>();

            if (input.Account > 0)
            {
                var user = await _userRepository.FindAsync(x => x.Account == input.Account);
                if (user != null)
                {
                    var ur = _userRelationRepository.FindAsync(x => x.Ancestor == userId && x.Descendant == user.Id);
                    if (ur != null)
                    {
                        data.Add(new TeamMemberInfoDto() { Id = user.Id, Account = user.Account, Head = user.Head, NickName = user.Nickname, Grade = user.Grade, JoinTime = user.CreatTime, Tel = user.Tel });
                        count = 1;
                    }                        
                }
            }
            else
            {
                string sql = @$" FROM usr_userRelation ur JOIN usr_user u ON ur.Descendant = u.Id WHERE ur.Ancestor = @user";
                dynamic p = new { };
                dynamic p2 = new { };
                if (string.IsNullOrWhiteSpace(input.Name) && input.Grade == 0)
                {
                    p = new { user = userId };
                    p2 = new { user = userId, skip = (input.PageIndex - 1) * input.PageSize, take = input.PageSize };
                }
                else if (string.IsNullOrWhiteSpace(input.Name) && input.Grade > 0)
                {
                    p = new { user = userId, input.Grade };
                    p2 = new { user = userId, input.Grade, skip = (input.PageIndex - 1) * input.PageSize, take = input.PageSize };
                }
                else if (!string.IsNullOrWhiteSpace(input.Name) && input.Grade > 0)
                {
                    p = new { user = userId, input.Grade, input.Name };
                    p2 = new { user = userId, input.Grade, input.Name, skip = (input.PageIndex - 1) * input.PageSize, take = input.PageSize };
                }
                else if (!string.IsNullOrWhiteSpace(input.Name) && input.Grade == 0)
                {
                    p = new { user = userId, input.Name };
                    p2 = new { user = userId, input.Name, skip = (input.PageIndex - 1) * input.PageSize, take = input.PageSize };
                }                   

                if (!string.IsNullOrWhiteSpace(input.Name))
                    sql += " AND u.Nickname LIKE concat( '%', @name, '%' )";

                if (input.Grade > 0)
                    sql += " AND u.Grade = @grade";

                string sql1 = @$"SELECT COUNT(1) AS num " + sql;
                string sql2 = $@"SELECT u.Id,u.Account,u.Grade,u.Head,u.Nickname,u.CreatTime as joinTime,u.Tel " + sql + " LIMIT @skip,@take";

                count = (await _userRepository.QueryAsync<int>(sql1, p))[0];
                data = await _userRepository.QueryAsync<TeamMemberInfoDto>(sql2, p2);
            }
            return new PageModelDto<TeamMemberInfoDto>(input, data, count);
        }

        /// <summary>
        /// 根据电话号码获取用户信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<UserNameAndHeadTelDto>> FindUserByPhone(string phone)
        {
            var user = await _userRepository.FindAsync(x => x.Tel.Equals(phone));
            if (user == null)
                return Problem(null, "该用户不存在");
            return new UserNameAndHeadTelDto {Id = user.Id, Head = user.Head,Name = user.Nickname , Tel = user.Tel};
        }
    }
}
